package com.zdd.chap7news.job;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;
@Slf4j
@Component
public class NewJob {
    protected final Logger logger= LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;
    //每分钟
    @Scheduled(cron = "0 0/1 * * * ?")
    public void SaveNewsData(){
        //获取所有以news_开头的键
        Set<String> keys=redisTemplate.keys("news_*");
        for(String key:keys){
            Map<String,String> map=redisTemplate.opsForHash().entries(key);
            //获取key中包含的id号，key是news_+id的格式
            String id=key.substring(5);
            String read=map.get("read");//获取阅读数
            String zan=map.get("zan");//获取点赞数
            //然后调用业务层将这些数据更新到数据库


            logger.info("编号："+id+"阅读次数："+read+"点赞次数："+zan);
        }
        logger.info("以上数据已保存到数据库！");
    }

}
